﻿@using SimpleIdServer.IdServer.Website.Resources;
@using SimpleIdServer.IdServer.Website.Shared.Dialogs
@using SimpleIdServer.IdServer.Website.Stores.UserStore;
@inherits Fluxor.Blazor.Web.Components.FluxorComponent
@inject IDispatcher dispatcher
@inject IState<UserCredentialsState> userCredentialsState
@inject DialogService dialogService
@inject IState<UpdateUserState> updateUserState
@inject ContextMenuService contextMenuService
@inject NotificationService notificationService

<p class="text-muted">
    @Global.UserCredentialsDescription
</p>

<SidAuthorizeView Roles=@($"/users/manage")>
    <Authorized>
        <RadzenButton class="mb-1" Click="@(args => AddCredential())" Icon="add" Text="@Global.AddCredential" ButtonStyle="ButtonStyle.Primary" Size="ButtonSize.Medium"></RadzenButton>
    </Authorized>
</SidAuthorizeView>

<RadzenDataGrid AllowFiltering="true" 
AllowColumnResize="true"
AllowAlternatingRows="false" 
AllowSorting="true" 
PageSize="30" 
AllowPaging="true" 
PagerHorizontalAlign="HorizontalAlign.Left" 
ShowPagingSummary="true"
FilterMode="FilterMode.Simple"
LogicalFilterOperator="LogicalFilterOperator.And"
FilterCaseSensitivity=FilterCaseSensitivity.CaseInsensitive
IsLoading="@updateUserState.Value.IsUpdating"
Count="@userCredentialsState.Value.Count"
Data="@userCredentialsState.Value.UserCredentials"
TItem="UserCredential" 
ColumnWidth="300px">
    <Columns>
        <RadzenDataGridColumn TItem="UserCredential" Title="@Global.Active" Filterable="false" Sortable="false" Width="80px" TextAlign="TextAlign.Center">
            <Template Context="data">
                <RadzenCheckBox @bind-Value=data.IsActive Change="@(args => Toggle(args, data))" TValue="bool" Disabled=@data.IsActive />
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="UserCredential" Title="@Global.Type" Property="CredentialType" Filterable="true" Sortable="false" Width="80px">
            <Template Context="data">
                @if(data.CredentialType == UserCredential.PWD)
                {
                    <span>@Global.Password</span>
                }
                else if(data.CredentialType == "webauthn")
                {
                    <span>@Global.WebAuthn</span>
                }
                else if (data.CredentialType == "mobile")
                {
                    <span>@Global.Mobile</span>
                }
                else
                {
                    <span>@Global.Otp</span>
                }
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="UserCredential" Title="@Global.Data" Filterable="false" Sortable="false" Width="80px">
            <Template Context="data">
                @if(data.CredentialType == UserCredential.OTP)
                {
                    <RadzenLink Text="@Global.ShowData" 
                    @onmousedown="() => ShowData(data)"
                    @onclick:preventDefault="true" />
                }
            </Template>
        </RadzenDataGridColumn>
        <RadzenDataGridColumn TItem="UserCredential" Filterable="false" Sortable="false" Width="80px" TextAlign="TextAlign.Center">
            <Template Context="data">
                <SidAuthorizeView Roles=@($"/users/manage")>
                    <Authorized>
                        <RadzenButton Icon="more_vert" Click="@(args => ShowMoreContextMenu(data, args))" />
                    </Authorized>
                </SidAuthorizeView>
            </Template>
        </RadzenDataGridColumn>
    </Columns>
</RadzenDataGrid>

@code {
    [Parameter]
    public SimpleIdServer.IdServer.Domains.User User { get; set; }

    protected override void OnAfterRender(bool firstRender)
    {
        base.OnAfterRender(firstRender);
        if (firstRender)
        {
            SubscribeToAction<RemoveUserCredentialSuccessAction>((act) =>
            {
                notificationService.Notify(new NotificationMessage { Severity = NotificationSeverity.Success, Summary = Global.UserCredentialRemoved });
                StateHasChanged();
            });
        }
    }

    void Toggle(bool isCheck, UserCredential credential)
    {
        dispatcher.Dispatch(new DefaultUserCredentialAction { CredentialId = credential.Id, UserId = User.Id });
    }

    async void ShowData(UserCredential credential)
    {
        await dialogService.OpenAsync<CredentialInfoDialog>(Global.Information, new Dictionary<string, object>
        {
            { "Credential", credential },
            { "User", User }
        }, new DialogOptions
        {
            Width = "700px",
            Height = "512px",
            Resizable = true,
            Draggable = true
        });
    }

    void ShowMoreContextMenu(UserCredential cred, MouseEventArgs args)
    {
        var contextMenuItems = new List<ContextMenuItem>
        {
            new ContextMenuItem { Text = Global.Delete, Value = 1 },
        };
        if (cred.CredentialType != "webauthn" && cred.CredentialType != "mobile") contextMenuItems.Add(new ContextMenuItem { Text = Global.Reset, Value = 2 });
        contextMenuService.Open(args, contextMenuItems, async (a) => {
            if (a.Value.Equals(1))
            {
                var act = new RemoveUserCredentialAction { CredentialId = cred.Id, UserId = User.Id };
                dispatcher.Dispatch(act);
                contextMenuService.Close();
            }
            else if(a.Value.Equals(2))
            {
                await dialogService.OpenAsync<EditCredentialDialog>(Global.UpdateCredential, new Dictionary<string, object>
            {
                { "UserId", User.Id },
                { "Credential", cred }
            }, new DialogOptions
            {
                Width = "700px",
                Height = "512px",
                Resizable = true,
                Draggable = true
            });
                contextMenuService.Close();
            }
        });
    }

    async void AddCredential()
    {
        await dialogService.OpenAsync<AddCredentialDialog>(Global.AddCredential, new Dictionary<string, object> { { "UserId", User.Id } }, new DialogOptions
        {
            Width = "700px",
            Height = "512px",
            Resizable = true,
            Draggable = true
        });
    }
}